<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { queryTopWithoutRankingCategoryList } from '@/service/category.js'
import { ElMessage } from 'element-plus'
import { addHotSaleRankingItem, updateHotSaleRankingItem } from '@/service/hot-sales-ranking.js'
const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
})
const emit = defineEmits(['update'])
const formRef = ref()
const showModal = ref(false)
const categoryList = ref([])

const form = reactive({
  categoryId: null,
  status: 0,
})
watch(showModal, (value) => {
  if (!value) {
    Object.assign(form, {
      categoryId: null,
      status: 0,
    })
  } else {
    loadCategoryList()
  }
})
async function loadCategoryList() {
  const res = await queryTopWithoutRankingCategoryList()
  categoryList.value = res.data
}

onMounted(() => {
  loadCategoryList()
})
const rules = reactive({
  categoryId: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  status: [{ required: true, message: '请选择分类', trigger: 'blur' }],
})

async function onTapUpdateButton() {
  console.log(form)
  await updateHotSaleRankingItem(form.categoryId, form.status)
  ElMessage.success('更新成功！')
  emit('update')
  showModal.value = false
}
async function onTapSaveButton() {
  try {
    await formRef.value.validate()
    await addHotSaleRankingItem(form.categoryId, form.status)
    ElMessage.success('添加成功！')
    emit('update')
    showModal.value = false
  } catch {}
}

defineExpose({
  showModal,
  form,
})
</script>

<template>
  <el-dialog v-model="showModal" :title="type === 'add' ? '新增热销条目' : '更新热销条目'" draggable width="800">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="right" label-width="100px">
      <el-form-item label="热销分类:" prop="categoryId">
        <el-select :disabled="type === 'edit'" v-model="form.categoryId" placeholder="请选择分类" style="width: 240px">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="0">展示</el-radio>
          <el-radio :value="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="type === 'add'" type="primary" @click="onTapSaveButton">保存</el-button>
      <el-button v-if="type === 'edit'" type="primary" @click="onTapUpdateButton"> 更新 </el-button>
      <el-button type="default" @click="showModal = false"> 取消 </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
